package com.cn.utils;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class EnglishSentenceUtil {

    public static String getSentenceTranslate(String query) throws Exception {
        String apiUrl = "https://dict.youdao.com/jsonapi?q=" + encodeQuery(query);
        URL url = new URL(apiUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        // Check the response code
        if (conn.getResponseCode() == 200) {
            // Read the response
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // Parse the JSON response
            JSONObject jsonResponse = new JSONObject(response.toString());
            System.out.println(jsonResponse);
            return jsonResponse.getJSONObject("fanyi").getString("tran");
        } else {
            throw new Exception("Error: " + conn.getResponseCode());
        }
    }

    // Helper method to encode the query for URL
    private static String encodeQuery(String query) {
        try {
            return java.net.URLEncoder.encode(query, "UTF-8");
        } catch (Exception e) {
            return query; // Fallback in case of error
        }
    }

    public static String getUsSentenceVoice(String sentence){
        String us_voice_pattern = "https://dict.youdao.com/dictvoice?type=0&audio=";
        return us_voice_pattern+sentence;
    }

    public static String getUkSentenceVoice(String sentence){
        String uk_voice_pattern = "https://dict.youdao.com/dictvoice?type=1&audio=";
        return uk_voice_pattern+sentence;
    }

    public static void main(String[] args) {
        String chineseSentence = "这是一本书"; // Your Chinese input
        try {
            String translation = getSentenceTranslate(chineseSentence);
            System.out.println("Translation: " + translation);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
